<template>
  <el-dialog :title="title" :visible.sync="visible" width="700px" :close-on-click-modal="false"
             :close-on-press-escape="true" @closed="handleClosed">
    <div v-loading="loading">
      <div class="mt--8">
        <div class="flex-x justify-start items-center gap-4">
          <h3>
          第{{ questionSortOrder }}题（{{ questionScore }}分）
          </h3>

          <div>
            <div class="flex-x gap-2">
              <el-button type="plain" size="mini" icon="el-icon-arrow-left" @click="handlePrevQuestion">上一题
              </el-button>
              <el-button type="plain" size="mini" icon="el-icon-arrow-right" @click="handleNextQuestion">下一题
              </el-button>
              <el-button type="primary" size="mini" @click="handleAddOption" icon="el-icon-plus">
                添加选项
              </el-button>
            </div>
          </div>
        </div>

        <div class="my-4">
        <Markdown :content="questionTitle"/>
      </div>
      </div>

      <div style="">
        <div v-for="(option, index) in optionsList" :key="index">
          <div class="flex-x justify-between items-center gap-4 my-2">
            <input name="id" type="hidden" :value="option.id">
            <span>{{ `选项 ${option.optionNum}` }}</span>

            <el-input v-model="option.content" class="flex-1" placeholder="选项内容"
                      @keyup.enter.native="handleOptionEnter(index)">
            </el-input>

            <span>正确答案
              <el-switch v-model="option.isAnswer" @change="(val) => handleAnswerChange(val, index)">
              </el-switch>
            </span>

            <el-button type="danger" icon="el-icon-delete" @click="handleDeleteOption(index)"
                       circle :focusable="false" size="mini">
            </el-button>
          </div>
        </div>

        <div class="mt-4">
            <el-input type="textarea" :rows="5" v-model="tmpText" placeholder="临时文本区"></el-input>
        </div>
      </div>
    </div>
    <div slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handleSave" :loading="loading">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/common/api'
import Markdown from '@/components/oj/common/Markdown.vue'

export default {
  name: 'OptionsDialog',
  components: {
    Markdown
  },
  data() {
    return {
      visible: false,
      loading: false,

      tmpText: '',

      question: {},

      questionTitle: '',
      questionId: null,
      questionType: null,
      questionSortOrder: null,
      questionScore: null,

      optionsList: [],
      title: '编辑选项'
    }
  },
  methods: {
    async open(row) {
      this.question = row || {}
      this.questionId = row.id
      this.questionTitle = row.title
      this.questionType = row.questionType
      this.questionScore = row.score
      this.questionSortOrder = row.sortOrder

      this.visible = true
      await this.loadOptions()

      // 如果没有选项，添加默认的ABCD四个选项
      if (this.optionsList.length === 0) {
        ['A', 'B', 'C', 'D'].forEach((letter, index) => {
          this.optionsList.push({
            questionId: this.questionId,
            optionNum: letter,
            content: '',
            sortOrder: index + 1,
            isCorrect: false
          })
        })
      }
    },
    async loadOptions() {
      try {
        this.loading = true
        const {data} = await api.admin_getItechCollQuestionOptionList({questionId: this.questionId})
        this.optionsList = data.data.records || []
        console.log('data', data)
      } finally {
        this.loading = false
      }
    },
    handleAddOption() {
      const nextLetter = String.fromCharCode(65 + this.optionsList.length)
      this.optionsList.push({
        questionId: this.questionId,
        optionNum: nextLetter,
        content: '',
        sortOrder: this.optionsList.length + 1,
        isCorrect: false
      })
    },
    handleDeleteOption(index) {
      this.optionsList.splice(index, 1)
      // 重新排序选项编号
      this.optionsList.forEach((option, idx) => {
        option.optionNum = String.fromCharCode(65 + idx)
        option.sortOrder = idx + 1
      })
    },
    handleAnswerChange(val, index) {
      // 单选题时只允许选择一个正确答案
      if (this.questionType === 1 && val) {
        this.optionsList.forEach((option, i) => {
          if (i !== index) {
            option.isCorrect = false
          }
        })
      }
    },
    handleOptionEnter(index) {
      if (index === this.optionsList.length - 1) {
        if (this.optionsList[index].content.trim()) {
          this.handleSave()
        }
      } else {
        this.$nextTick(() => {
          const inputs = this.$el.querySelectorAll('.el-input__inner')
          if (inputs[index + 1]) {
            inputs[index + 1].focus()
          }
        })
      }
    },

    async handlePrevQuestion() {
      await this.handleQuestion('prev')
    },

    async handleNextQuestion() {
      await this.handleQuestion('next')
    },

    async handleQuestion(direction) {
      const params = {
        collId: this.question.collId,
        sortOrder: direction === 'prev' ? this.questionSortOrder - 1 : this.questionSortOrder + 1,
        questionTypes: '1,2'
      }

      const {data} = await api.admin_getItechCollQuestionDetail(params)
      if (!data.data) {
        this.$message.warning(direction === 'prev' ? '没有上一题了' : '没有下一题了')
      } else {
        this.open(data.data)
      }
    },

    async handleSave() {
      // 验证
      if (this.optionsList.length < 2) {
        this.$message.warning('至少需要两个选项')
        return
      }
      if (this.optionsList.some(option => !option.content.trim())) {
        this.$message.warning('请填写所有选项内容')
        return
      }
      const correctCount = this.optionsList.filter(option => option.isAnswer).length
      if (this.questionType === 1 && correctCount !== 1) {
        this.$message.warning('单选题必须有一个正确答案')
        return
      }
      if (this.questionType === 2 && correctCount < 2) {
        this.$message.warning('多选题至少需要两个正确答案')
        return
      }

      try {
        this.loading = true
        await api.admin_saveItechCollQuestionOption({
          questionId: this.questionId,
          optionList: this.optionsList
        })
        this.$message.success('保存成功')
        this.tmpText = ''
        this.$emit('success')
      } finally {
        this.loading = false
      }
    },
    handleClosed() {
      this.optionsList = []
      this.questionId = null
      this.questionType = null
    }
  }
}
</script>
